<template>
    <div class="pageCon">
        <div style="width: 100%;">
            <el-date-picker v-model="dateRangeExport" type="daterange" range-separator="到" start-placeholder="开始日期"
                end-placeholder="结束日期" />
            <el-button type="primary" style="margin-left: 2px;" @click="getUserDateList()">时间区间筛选</el-button>
            <el-button type="primary" style="margin-left: 20px;"
                @click="findDetailDateDialogVisible = true">定位与修改</el-button>
            <el-button type="success" style="margin-left: 20px;"
                @click="exportDialogVisible = true">导出时间区间内所有订餐数据</el-button>
            <el-button type="warning" style="margin-left: 20px;" @click="ifUpdatePrice = true">价格与订餐时间修改</el-button>
            <!-- 导出数据弹窗 -->
            <el-dialog v-model="exportDialogVisible" title="导出数据" width="30%">
                <el-form>
                    <el-form-item label="时间区间">
                        <el-date-picker v-model="exportDateRange" type="daterange" range-separator="到"
                            start-placeholder="开始日期" end-placeholder="结束日期" />
                    </el-form-item>
                    <el-button type="primary" @click="exportData">导出</el-button>
                </el-form>
            </el-dialog>
            <el-dialog v-model="findDetailDateDialogVisible" title="查询与修改" width="30%">
                <el-form>
                    <el-form-item label="日期">
                        <el-date-picker v-model="detailDate" type="date" placeholder="选择日期"
                            :disabled-date="disabledDate" />
                    </el-form-item>
                    <el-form-item label="工号">
                        <el-input v-model="detailJobNumber" placeholder="请输入工号" />
                    </el-form-item>
                    <!-- <el-form-item label="姓名">
                        <el-input v-model="detailName" placeholder="请输入工号" />
                    </el-form-item> -->
                    <el-button type="primary" @click="searchDetailDate">查询</el-button>
                    <el-button type="danger" @click="clearDate">清除搜索条件</el-button>
                </el-form>
                <el-table border :data="searchDetailAns" style="width: 100%;margin-top: 20px;"
                    v-if="searchDetailAns.length">
                    <el-table-column prop="name" label="姓名" width="70px" />
                    <el-table-column prop="jobNumber" label="工号" />
                    <el-table-column prop="breakfast" label="早餐">
                        <template #default="{ row }">
                            <!-- {{ row.breakfast ? '1' : '' }} -->
                            <el-button v-if="!row.breakfast" type="primary"
                                @click="handleOrder(detailDate, 'breakfast')">
                                预约
                            </el-button>
                            <el-button v-else type="danger" @click="handleCancel(detailDate, 'breakfast')">
                                取消预约
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="breakfast" label="午餐">
                        <template #default="{ row }">
                            <!-- {{ row.breakfast ? '1' : '' }} -->
                            <el-button v-if="!row.lunch" type="primary" @click="handleOrder(detailDate, 'lunch')">
                                预约
                            </el-button>
                            <el-button v-else type="danger" @click="handleCancel(detailDate, 'lunch')">
                                取消预约
                            </el-button>
                        </template>
                    </el-table-column> <el-table-column prop="breakfast" label="晚餐">
                        <template #default="{ row }">
                            <el-button v-if="!row.dinner" type="primary" @click="handleOrder(detailDate, 'dinner')">
                                预约
                            </el-button>
                            <el-button v-else type="danger" @click="handleCancel(detailDate, 'dinner')">
                                取消预约
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-dialog>
            <el-dialog v-model="ifUpdatePrice" title="修改价格与订餐时间" width="30%">
                <el-form>
                    <el-form-item label="食堂名称">
                        <el-input v-model="restaurantName" placeholder="请输入食堂名称" />
                    </el-form-item>
                    <el-form-item label="早餐">
                        <el-input v-model="breakfastPrice" placeholder="请输入早餐价格" />
                    </el-form-item>
                    <el-form-item label="中餐">
                        <el-input v-model="lunchPrice" placeholder="请输入中餐价格" />
                    </el-form-item>
                    <el-form-item label="晚餐">
                        <el-input v-model="dinnerPrice" placeholder="请输入晚餐价格" />
                    </el-form-item>
                    <el-form-item label="早餐">
                        <el-select v-model="breakfastTime.day" style="width: 100px;">
                            <template #label>
                                <span>{{ breakfastTime.day === '1' ? '当天' :
                                    '前一天' }}</span>
                            </template>
                            <el-option v-for="item in dayOptions" :label="item.label" :value="item.value"
                                :key="item.value">
                                {{ item.label }}
                            </el-option>
                        </el-select>
                        <el-input v-model="breakfastTime.time" placeholder="请输入早餐时间" style="width: 100px;" type="number"
                            max="24" min="1" />点
                    </el-form-item>
                    <el-form-item label="午餐">
                        <el-select v-model="lunchTime.day" style="width: 100px;">
                            <template #label>
                                <span>{{ lunchTime.day === '1' ? '当天' :
                                    '前一天' }}</span>
                            </template>
                            <el-option v-for="item in dayOptions" :label="item.label" :value="item.value"
                                :key="item.value">
                                {{ item.label }}
                            </el-option>
                        </el-select>
                        <el-input v-model="lunchTime.time" placeholder="请输入午餐时间" style="width: 100px;" type="number"
                            max="24" min="1" />点
                    </el-form-item>
                    <el-form-item label="晚餐">
                        <el-select v-model="dinnerTime.day" style="width: 100px;">
                            <template #label>
                                <span>{{ dinnerTime.day === '1' ? '当天' :
                                    '前一天' }}</span>
                            </template>
                            <el-option v-for="item in dayOptions" :label="item.label" :value="item.value"
                                :key="item.value">
                                {{ item.label }}
                            </el-option>
                        </el-select>
                        <el-input v-model="dinnerTime.time" placeholder="请输入晚餐时间" style="width: 100px;" type="number"
                            max="24" min="1" />点
                    </el-form-item>
                    <el-button type="primary" @click="updatePrice">修改</el-button>
                </el-form>
            </el-dialog>
        </div>

        <el-table border :data="tableData" style="width: 90%;margin-top: 20px;">
            <el-table-column prop="user" label="姓名">
                <template #default="{ row }">
                    {{ row.user.name }}
                </template>
            </el-table-column>
            <el-table-column prop="user" label="工号">
                <template #default="{ row }">
                    {{ row.user.jobNumber }}
                </template>
            </el-table-column>
            <el-table-column prop="breakfast" :label='"早餐" + breakfastPrice + "(元)"' />
            <el-table-column prop="lunch" :label='"午餐" + lunchPrice + "(元)"' />
            <el-table-column prop="dinner" :label='"晚餐" + dinnerPrice + "(元)"' />
        </el-table>
        <div style="width:90%;margin-top: 20px;">
            <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
                @current-change="handlePageChange" />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive, computed } from 'vue'
import { getRange } from '@/utils/getRange.js'
import { Api } from '@/api';
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
const disabledDate = (time) => {
    return time.getTime() > Date.now()
}
const findDetailDateDialogVisible = ref(false)
const ifUpdatePrice = ref(false)
const breakfastPrice = ref('')
const lunchPrice = ref('')
const dinnerPrice = ref('')
const restaurantName = ref('')
const timeForm = ref([])
const dayOptions = ref([{ label: '前一天', value: '0' }, { label: '当天', value: '1' }])
const breakfastTime = reactive({
    day: 0,
    time: 0
})
const lunchTime = reactive({
    day: 0,
    time: 0
})
const dinnerTime = reactive({
    day: 0,
    time: 0
})

const turnTime = (num) => {
    if (num > 0) {
        return { day: '0', time: (24 - num) }
    } else {
        return { day: '1', time: (0 - num) }
    }
}
const turnAnsTime = (obj) => {
    if (obj.day === '0') {
        return 24 - obj.time
    } else {
        return 0 - obj.time
    }
}
const updatePrice = () => {

    const temp = {
        breakfastPrice: breakfastPrice.value,
        lunchPrice: lunchPrice.value,
        dinnerPrice: dinnerPrice.value,
        breakfastTime: turnAnsTime(breakfastTime),
        lunchTime: turnAnsTime(lunchTime),
        dinnerTime: turnAnsTime(dinnerTime),
        restaurantName: restaurantName.value
    }
    console.log(temp);

    Api.updatePrice(temp).then(res => {
        if (res.status === 200) {
            ElMessage({
                message: res.message,
                type: 'success'
            })
            ifUpdatePrice.value = false
            _getPrice()
        }
    })
}
const _getPrice = () => {
    Api.getPrice().then(res => {
        if (res.status === 200) {
            breakfastPrice.value = res.data.breakfast
            lunchPrice.value = res.data.lunch
            dinnerPrice.value = res.data.dinner
            breakfastTime.day = turnTime(res.data.breakfastTime).day
            breakfastTime.time = turnTime(res.data.breakfastTime).time
            lunchTime.day = turnTime(res.data.lunchTime).day
            lunchTime.time = turnTime(res.data.lunchTime).time
            dinnerTime.day = turnTime(res.data.dinnerTime).day
            dinnerTime.time = turnTime(res.data.dinnerTime).time
            restaurantName.value = res.data.restaurantName
        }
    })
}

const exportDialogVisible = ref(false) // 导出数据弹窗的显示状态
const exportDateRange = ref(null) // 导出的时间区间

const exportData = () => {
    if (!exportDateRange.value) {
        ElMessage({
            message: '请选择时间区间',
            type: 'warning'
        })
        return
    }

    const temp = {
        firstDay: new Date(new Date(exportDateRange.value[0]).getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        lastDay: new Date(new Date(exportDateRange.value[1]).getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        page: 1,
        pageSize: 99999
    }

    Api.exportUserDish(temp).then(res => {
        if (res.status === 200) {
            const data = res.data.map(item => ({
                姓名: item.user.name,
                工号: item.user.jobNumber,
                早餐: item.breakfast,
                午餐: item.lunch,
                晚餐: item.dinner
            }));

            const worksheet = XLSX.utils.json_to_sheet(data);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
            XLSX.writeFile(workbook, `${temp.firstDay}至${temp.lastDay}餐饮预约数据.xlsx`);
            ElMessage.success('导出成功');
        }
    }).catch(error => {
        ElMessage.error('导出失败');
    }).finally(() => {
        exportDialogVisible.value = false;
    });
}
const dateRangeExport = ref()
const tableData = ref([])
const page = ref(1)
const pageSize = ref(15) // 每页显示的数据量
const total = ref(0) // 总数据量


const detailDate = ref('')
const detailJobNumber = ref('')
const detailUserId = ref('')
const searchDetailAns = ref([])
const searchDetailDate = () => {
    if (!detailDate.value) {
        ElMessage({
            message: '日期必填',
            type: 'warning'
        })
        return
    }
    if (!detailJobNumber.value) {
        ElMessage({
            message: '工号必填',
            type: 'warning'
        })
        return
    }


    const temp = {
        date: new Date(new Date(detailDate.value).getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        jobNumber: detailJobNumber.value,
    }
    Api.searchDetailUserDateDish(temp).then(res => {
        if (res.status === 200) {
            ElMessage({
                message: res.message,
                type: 'success'
            })
            searchDetailAns.value = res.data
            detailUserId.value = res.data[0].userId
        }
    })
}
const clearDate = () => {
    detailDate.value = ''
    detailJobNumber.value = ''
    searchDetailAns.value = []
    detailUserId.value = ''
}

onMounted(() => {
    // 拿到当天日期的月份的第一天
    const newDate = new Date(); // 获取当前日期
    const newDateStart = new Date(newDate.getFullYear(), newDate.getMonth(), 1); // 设置日期为当月的第一天
    const lastDayMonth = new Date(newDate.getFullYear(), newDate.getMonth() + 1, 0); // 获取当月最后一天
    // console.log(newDateStart);
    dateRangeExport.value = [
        newDateStart,
        lastDayMonth
    ]
    getUserDateList()
    _getPrice()
})
// closed返回回调有问题
watch(findDetailDateDialogVisible, (newVal, oldVal) => {
    if (newVal === false) {
        getUserDateList()
    }
})

const getUserDateList = () => {
    const temp = {
        firstDay: new Date(new Date(dateRangeExport.value[0]).getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        lastDay: new Date(new Date(dateRangeExport.value[1]).getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        page: page.value,
        pageSize: pageSize.value
    }
    Api.exportUserDish(temp).then(res => {
        if (res.status === 200) {
            tableData.value = res.data
            total.value = res.total
        }
    })
}

const handlePageChange = (newPage) => {
    page.value = newPage
    getUserDateList()
}

const handleOrder = (date, type) => {
    console.log(date, type, detailUserId.value);

    Api.orderDate({ userId: detailUserId.value, date, type }).then(res => {
        if (res.status == 200) {
            ElMessage.success('预定成功')
            searchDetailDate()
        }
    })
}
const handleCancel = (date, type) => {
    Api.cancelDate({ userId: detailUserId.value, date, type }).then(res => {
        if (res.status == 200) {
            ElMessage.success('取消成功')
            searchDetailDate()
        }
    })
}
</script>

<style scoped lang="scss">
.pageCon {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
}
</style>